package com.weex.app.extend;


import android.util.Log;
import android.widget.Toast;

import com.taobao.weex.annotation.JSMethod;
import com.taobao.weex.common.WXModule;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.weex.app.util.Constants;

import org.json.JSONObject;


public class WXPayModule extends WXModule {


  private IWXAPI api;

  @JSMethod()
  public void register() {
    api = WXAPIFactory.createWXAPI(mWXSDKInstance.getContext(), null);

    // 将该app注册到微信
    Boolean ifReg = api.registerApp(Constants.APP_ID);
    if(!ifReg) {
      Toast.makeText(mWXSDKInstance.getContext(),"注册失败",Toast.LENGTH_SHORT).show();
    }
  }

  @JSMethod()
  public void sendPay(String content) {
    try{
      if (content != null) {
        Log.e("get server pay params:",content);
        JSONObject json = new JSONObject(content);
        if(null != json && !json.has("retcode") ){
          PayReq req = new PayReq();
          req.appId			= json.getString("appid");
          req.partnerId		= json.getString("partnerid");
          req.prepayId		= json.getString("prepayid");
          req.nonceStr		= json.getString("noncestr");
          req.timeStamp		= json.getString("timestamp");
          req.packageValue	= json.getString("package");
          req.sign			= json.getString("sign");
          api.sendReq(req);
        }else{
          Log.d("PAY_GET", "返回错误"+json.getString("retmsg"));
          Toast.makeText(mWXSDKInstance.getContext(),"返回错误"+json.getString("retmsg"),Toast.LENGTH_SHORT).show();
        }
      }else{
        Log.d("PAY_GET", "服务器请求错误");
        Toast.makeText(mWXSDKInstance.getContext(),"服务器请求错误",Toast.LENGTH_SHORT).show();
      }
    }catch(Exception e){
      Log.e("PAY_GET", "异常："+e.getMessage());
      Toast.makeText(mWXSDKInstance.getContext(),"异常："+e.getMessage(),Toast.LENGTH_SHORT).show();
    }
  }
}
